package com.wnxy.controller;

import com.alibaba.druid.util.StringUtils;
import com.wnxy.domain.User;
import com.wnxy.service.IAuthService;
import com.wnxy.util.ResultVO;
import com.wnxy.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * @Classname AuthController
 * @Description :
 * @Date 2021/2/23 18:18
 * @Created by Yeheng
 */
@Controller
public class AuthController {

    private Set<String> logoutToken = new HashSet<>();

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    IAuthService service;

    @GetMapping("/auth")
    public String auth(String backUrl,String token_r){
        // 获取token，如果没有，就跳到登录界面
        String token = token_r;

        if (!StringUtils.isEmpty(token)) {
            boolean b = JwtUtils.verifyToken(token);
            if(b) {
                // 如果校验通过，则直接调回“来时的路”
                // 把这个token带在url的后面
                return "redirect:"+backUrl+"?token="+token;
            } else {
                // 如果校验没有通过，则直接调回“来时的路”
                return "login";
            }
        }
        // /templates/login.html
        return "login";


    }

    @PostMapping("/login")
    public String login(String backUrl, String username, String password, HttpServletResponse resp){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        if (service.findOne(user)==null){
            //8000
            return "/login";
        }
        String token = JwtUtils.createToken(username,1800);
        Cookie tokenCookie = new Cookie("token", token);
        resp.addCookie(tokenCookie);
        //登录成功返回token，下次其他微服务就会带着token去验证
        return "redirect:"+backUrl+"?token="+token;
    }

    @GetMapping("/verify")
    @ResponseBody
    public String verify(String token,HttpSession session){

        if (logoutToken.contains(token)){
            return false+"";
        }
        Object username = session.getAttribute("logout");
        return JwtUtils.verifyToken(token)+"";
    }

    @GetMapping("/logout")
    @ResponseBody
    public String logout(String token){
        System.out.println(token);
        logoutToken.add(token);
        System.out.println(11111111);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                logoutToken.remove(token);
            }
        } ,36000000L);
        return true+"";
    }

    @GetMapping("/test")
    @ResponseBody
    public String test(){
        String lock = "lock";
        Object uu = redisTemplate.opsForValue().get("uu");
        //防止直接服务器挂掉导致锁没释放
        Boolean lock1 = redisTemplate.opsForValue().setIfAbsent("lock", "1",9, TimeUnit.SECONDS);
        while (!lock1){
            try{
                Thread.sleep(50);
                wait();
            } catch(Exception e){
                e.printStackTrace();
            }
            lock1 = redisTemplate.opsForValue().setIfAbsent("lock", "1");
        }
        return uu.toString();
    }

    @PostMapping("/login2")
    @ResponseBody
    public ResultVO login2(@RequestBody User user){
        /*redisTemplate.opsForValue().get("")
        if (){

        }
        if (service.findOne(user)==null){

            return null;
        }
        String token = JwtUtils.createToken(user.getUsername(),1800);*/


        //登录成功返回token，下次其他微服务就会带着token去验证
        return null;
    }

}
